package com.huidu.bitrade.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huidu.bitrade.constant.MemberLevelEnum;
import com.huidu.bitrade.entity.*;
import com.huidu.bitrade.enums.MemberStarEnum;
import com.huidu.bitrade.exception.ServiceException;
import com.huidu.bitrade.mapper.HdzImportMapper;
import com.huidu.bitrade.service.*;
import com.huidu.bitrade.util.GeneratorUtil;
import com.huidu.bitrade.util.IdWorkByTwitter;
import com.huidu.bitrade.util.Md5;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
@Slf4j
public class HdzImportServiceImpl extends ServiceImpl<HdzImportMapper, HdzImport> implements HdzImportService {

    private final MemberService memberService;
    private final ActivityHdzOrderService activityHdzOrderService;
    private final MemberImportService memberImportService;
    private final AcMemberService acMemberService;
    private final MemberWalletService memberWalletService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void hdzImport(HdzImport hdzImport,List<Coin> coins,Activity activity) throws Exception {
        //查询用户是否存在
        Member member = memberService.findByPhone(hdzImport.getMobilePhone());
        if(Objects.isNull(member)){//创建账号
            member = memberImportService.createMember(hdzImport.getMobilePhone(),coins);
        }else{
            //查询是否有钱包，没有则创建
            List<MemberWallet> walletList = memberWalletService.findAllByMemberId(member.getId());
            if(CollectionUtils.isEmpty(walletList)){
                memberImportService.setWallet(coins,member.getId());
            }
        }
        //hdz锁仓
        if(hdzImport.getHdzLock().compareTo(BigDecimal.ZERO)>0){
            hdzLock(hdzImport.getHdzLock(),member.getId(),activity);
        }
        //给用户添加星级
        if(Objects.nonNull(hdzImport.getStar())){
            //扣除hdz
            MemberWallet memberWallet =memberWalletService.findByCoinUnitAndMemberId("HDZ",member.getId());
            if(Objects.nonNull(hdzImport.getSubHdz())&&hdzImport.getSubHdz().compareTo(BigDecimal.ZERO)>0&&memberWallet.getBalance().compareTo(hdzImport.getSubHdz())<0){
                //修改此条记录状态为2
                hdzImport.setStatus(2);
                hdzImport.setHdzLock(BigDecimal.ZERO);
                updateById(hdzImport);
                return ;
            }
            //判断星级
            if(Objects.nonNull(hdzImport.getOldStar())&&!hdzImport.getOldStar().equals(member.getMemberStar())){
                //修改此条记录状态为3
                hdzImport.setStatus(3);
                hdzImport.setHdzLock(BigDecimal.ZERO);
                hdzImport.setSubHdz(BigDecimal.ZERO);
                updateById(hdzImport);
                return ;
            }
            if(Objects.nonNull(hdzImport.getSubHdz())&&hdzImport.getSubHdz().compareTo(BigDecimal.ZERO)>0){
                //扣除hdz
                memberWallet.setBalance(memberWallet.getBalance().subtract(hdzImport.getSubHdz()));
            }
            setStar(member,hdzImport.getStar());
        }
        //修改此条记录状态为已导入
        hdzImport.setStatus(1);
        hdzImport.setHdzLock(BigDecimal.ZERO);
        updateById(hdzImport);
    }


    /**
     * 处理hdz锁仓（50%节点购买，50%hdz质押）
     */
    private void hdzLock(BigDecimal amount,Long memberId,Activity activity){
        if(amount.compareTo(BigDecimal.ZERO)>0){
            //计算出一半
//            BigDecimal half = amount.divide(BigDecimal.valueOf(2),8, RoundingMode.DOWN);
            //参与hdz质押活动
            createHdzOrder(amount,memberId,activity);
            //购买节点hdz余额添加
//            createNodeHdz(half,memberId);
        }
    }

    /**
     * 给用户升星级
     */
    private void setStar(Member member,Integer star) throws ServiceException {
        MemberStarEnum starEnum = MemberStarEnum.getByLevel(star);
        acMemberService.purchaseImport(member,starEnum.getCount(),1);
    }

    /**
     * 创建hdz质押活动
     */
    private void createHdzOrder(BigDecimal half,Long memberId,Activity activity){
        activityHdzOrderService.save(ActivityHdzOrder.builder()
                .memberId(memberId)
                .activityId(activity.getId())
                .number(half)
                .symbol(activity.getAcceptUnit())
                .status(1)
                .currentNumber(half)
                .build());
    }

    /**
     * 添加购买节点hdz余额
     */
//    private void createNodeHdz(BigDecimal half,Long memberId){
//        acNodeHdzService.save(AcNodeHdz.builder().memberId(memberId).hdz(half).build());
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void hdzImport2(HdzImport hdzImport, Activity activity) {
        //查询用户是否存在
        Member member = memberService.findByPhone(hdzImport.getMobilePhone());
        //参与hdz质押活动
        if(hdzImport.getHdzLock().compareTo(BigDecimal.ZERO)>0){
            createHdzOrder(hdzImport.getHdzLock(), member.getId(), activity);
        }
        hdzImport.setStatus(1);
        hdzImport.setHdzLock(BigDecimal.ZERO);
        updateById(hdzImport);
    }
}
